package com.system_jsp.control;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.system_jsp.bean.UserBean;
import com.system_jsp.dao.UserDao;
import com.system_jsp.util.MD5;

/**
 * Servlet implementation class LoginProcess
 */
@WebServlet(description = "登陆处理", urlPatterns = { "/LoginProcess" })
public class LoginProcess extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username, passwd, flag;
		username = request.getParameter("username");
		passwd = MD5.md5Encode(request.getParameter("passwd"));
		flag = request.getParameter("flag");

		UserBean ub = new UserDao().login(username);

		if (ub != null) {// 用户名正确
			if (ub.getPasswd().equals(passwd)) {// //用户名密码正确
				
				request.getSession().setAttribute("username", username);
				
				if (flag != null && flag.equals("checked")) { // 30天免登录
					Cookie cookie = new Cookie("username", username);
					cookie.setMaxAge(3600 * 24 * 30);
					response.addCookie(cookie);
				}
				response.sendRedirect("./UserList?page=1");
			} else { // 密码错误
				response.sendRedirect("./index.jsp?error=passerror");
			}
		} else { // 用户不存在
			response.sendRedirect("./index.jsp?error=usererror");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
